[#ftl]
[#--include "../../util.ftl"/--]
[#include "GridHeader.ftl"/]
[#include "GridBody.ftl"/]

[@define "agile.grid.DataGrid" "agile._Component,agile._Container,agile._Resizable,agile._ContainerToolbar"] 
  widgetName:"DataGrid"
  [#assign templateString]
  <div class="agileComponent agileDataGrid" style="overflow:auto;width:{style.width};height:{style.height}">
   		<div data-dojo-attach-point="containerNode,headerNode" style="width:100%;height:23px"></div>
  </div>
  [/#assign]
  ,templateString: "${templateString?js_string}"
  ,sortAxis:"x"
  // ,columnCount:0
  ,_lastColumnIndex:0
  ,headerColumns:null	  
  ,structure:null
  ,store:null
  ,templateMap:{
	 dojo:"<div {id} {html-style}><table data-dojo-type='{dojoDeclaredClass}' data-dojo-props='{props}'>{thead}{tbody}</table></div>"
  	,agile:"<table data-dojo-type='{declaredClass}' data-dojo-props='{style-props}'>{thead}{tbody}</table>\n"
  }	  
 ,styleConstraints:agile.delegate(agile._Component.prototype.styleConstraints,{
//		"height":{_important:true}
// 		,"width":{_important:true}
	})
  ,attributes:agile.delegate(agile._Component.prototype.attributes,{
  	store:lang.mixin({},agile.TextMetadata,{
  		_hidden:true,
  		onValueChange:function(widget,name,value){	
  			widget.metadata("parameters."+name,value);
  		}
  	})
  	,rowSelector:lang.mixin({},agile.NumberMetadata,{			
  		unit:"px",positive:true
  		,label:"i18n_row_selector"
  		,onValueChange:function(widget,name,value){	
  			widget.metadata("parameters."+name,value);
  			widget.adjustRowSelector();
  		}
  	})
  	,selectionMode:lang.mixin({},agile.ComboMetadata,{	
  		label:"i18n_selection_mode"
  		,options: agile.i18nMap(["none","single","multiple","extended"],null,true)
  		,onValueChange:function(widget,name,value){	
  			widget.metadata("parameters."+name,value);					
  		}
  	})
  	,headerMenu:lang.mixin({},agile.TextMetadata,{	
  		_hidden:true
  		,label:"i18n_header_menu"
  		,onValueChange:function(widget,name,value){	
  			widget.metadata("parameters."+name,value);
  		}
  	})
  	,autoHeight:lang.mixin({},agile.BooleanMetadata,{	
  		label:"i18n_auto_height"
  		,onValueChange:function(widget,name,value){	
  			widget.metadata("parameters."+name,value);
  		}
  		,ignore:function(widget,sourceType){
  			return !widget.metadata("parameters.autoHeight");
  		}
  	})
  	,autoWidth:lang.mixin({},agile.BooleanMetadata,{		
  		label:"i18n_auto_width"
  		,onValueChange:function(widget,name,value){	
  			widget.metadata("parameters."+name,value);
  		}
  		,ignore:function(widget,sourceType){
  			return !widget.metadata("parameters.autoWidth");
  		}
  	})
  	,singleClickEdit:lang.mixin({},agile.BooleanMetadata,{
  		label:"i18n_single_click_edit"
  		,onValueChange:function(widget,name,value){	
  			widget.metadata("parameters."+name,value);
  		}
  		,ignore:function(widget,sourceType){
  			return !widget.metadata("parameters.singleClickEdit");
  		}
  	})
  	,loadingMessage:lang.mixin({},agile.TextMetadata,{	
  		_hidden:true
  		,label:"i18n_loading_message"
  		,onValueChange:function(widget,name,value){	
  			widget.metadata("parameters."+name,value);
  		}
  	})
  	,errorMessage:lang.mixin({},agile.TextMetadata,{
  		_hidden:true
  		,label:"i18n_error_message"
  		,onValueChange:function(widget,name,value){	
  			widget.metadata("parameters."+name,value);
  		}
  	})			
  })
  ,_getDelegatePrototype:function(){
	  agile.requireX("dojox.grid.DataGrid");
	  agile.requireX("dojo.store.Memory");
	  agile.requireX("dojo.data.ObjectStore");
	  	
	return dojox.grid.DataGrid.prototype;
  }
  ,initDefaultMetadata:function(){
	  	this.metadata("parameters.caption","Caption");
	  	this.metadata("parameters.rowSelector","0px");
	  	// default width and height
	  	this.metadata("style.width","250px");
	  	this.metadata("style.height","200px");
	  	this.metadata("dojoDeclaredClass","dojox.grid.DataGrid");
  }
  ,constructor:function(params,node){
	  ////console.log(this.declaredClass,"[agile.grid.DataGrid]:constructor....");	  	
	  	this.structure = [];
	  	this.headerColumns = [];

	  	if(node){
			//create the headers according to the html template
			query("th",node).forEach(function(th,idx){						
		  		this.headerColumns.push(new agile.grid.GridHeader({
					field:attr.get(th,"field")
					,width:attr.get(th,"width")
					,editable:attr.get(th,"editable")=="true"
					,hidden:attr.get(th,"width")=="0px"
					,header: th.innerHTML
					,index:idx
				}));	  		
			},this);
			
			construct.empty(node);
			
	  	}
		//create the default headers if there is no headers in the template
		if(this.headerColumns.length == 0){			
			array.forEach([{field:"_id",width:"0px",editable:false,hidden:true,header:"ID",index:1}
	  					,{field:"f1",width:"100px",editable:true,hidden:false,header:"header1",index:2}
	  					,{field:"f2",width:"100px",editable:true,hidden:false,header:"header2",index:3}]
						,function(th){
				this.headerColumns.push(new agile.grid.GridHeader(th));
			},this);	  		
		}	
		
		//add the headers to the widget
		aspect.after(this,"postCreate",lang.hitch(this,function(){
			for(var i = 0; i < this.headerColumns.length; i++){
				this.addComponent(this.headerColumns[i]);	
			}
			
			this.gridBody = new agile.grid.GridBody({parent:this});
		    construct.place(this.gridBody.domNode,this.domNode,"last");
			this.gridBody.startup();				
		}));
				
	  	this.watch("store",function(name,oldValue,newValue){
	  		this.gridBody.refreshData();
	  	});	  	
  }		
	,onChildAdded:function(child){		
		//summary:add column  together with the header
//		console.log(this.declaredClass,"##onChildAdded",child);
		this.gridBody.addColumn(child);
		this.adjustColumns();	
	}	
	,onChildRemoved:function(column){	
		//summary:remove column together with the header
//		console.log(this.declaredClass,"##onChildRemoved",column);
		this.gridBody.removeColumn(column);
//  		construct.destroy(column.domNode);
	  	this.adjustColumns();	
	}
//  ,postCreate:function(){	
//	  	var headerMetadata = [];
//	  	// //console.log("this.containerNode=",this.containerNode.innerHTML);
//	  	query("th",this.containerNode).forEach(function(node,index){
//	  		var metadata = {
//				field:attr.get(node,"field")
//				,width:attr.get(node,"width")
//				,editable:attr.get(node,"editable")=="true"
//				,hidden:attr.get(node,"width")=="0px"
//	  		};
//	  		
//	  		if(!metadata.header){
//	  			metadata.header = node.innerHTML;
//	  		}
//	  		headerMetadata[headerMetadata.length] = metadata;
//	  	},this);
//	  	
//	  	if(headerMetadata.length == 0){
//	  		headerMetadata[0] = {field:"_id",width:"0px",editable:false,_hidden:true,header:"ID"};
//	  		headerMetadata[1] = {field:"f1",width:"100px",editable:true,_hidden:false,header:"header1"};
//	  		headerMetadata[2] = {field:"f2",width:"100px",editable:true,_hidden:false,header:"header2"};  		
//	  	}
//	
//	  	this.containerNode.innerHTML = "";
//	  	
//	  	array.forEach(headerMetadata,function(header,index){
//	  		var headerColumn = new agile.grid.GridHeader({parameters:header},construct.create("div",{innerHTML:""}));
//	  		headerColumn.metadata("index",index);
//	  		this.headerColumns.push(headerColumn);
//	  	},this);
//	// throw new Error("test");
//  }
//  ,postInitToolbar:function(){
//	  this.addButton.title = agile.i18n("add_btn_tooltip",["column"],true);
//   }
  ,showControlButtons:function(child){
		if(child){
			//style.set(this.removeButton,{display:"none"});	
			style.set(this.removeButton,{display:"inline",position:"absolute",right:"5px"});						
			construct.place(this.removeButton,child.getToolbarAnchorNode(),"last");
			this.selectedChild = child;
		}else{
			style.set(this.removeButton,{display:"none"});	
			style.set(this.addButton,{display:"inline",position:"absolute"});						
			construct.place(this.addButton,this.getToolbarAnchorNode(),"last");
		}
	}
  ,init:function(){

//		for(var i = 0; i < this.headerColumns.length; i++){
//			this.addComponent(this.headerColumns[i]);	
//		}
	    this._lastColumnIndex = this.headerColumns.length;

//	    this.gridBody = new agile.grid.GridBody({parent:this});
//	    construct.place(this.gridBody.domNode,this.domNode,"last");
//		this.gridBody.startup();
	    style.set(this.domNode,{width:this.metadata("style.width"),height:this.metadata("style.height")});  	
	
	    this.moveColumn(this.headerColumns[this.headerColumns.length - 1]);
	    
	    this.showControlButtons();
  }

  ,adjustColumns:function(){
  	var columns = this.sortChildren();
  	array.forEach(columns,function(column,index){
  		column.metadata("index",index);  		
  		//console.log("####column[left,width]",column.metadata("parameters.header"),column.metadata("style.left"),column.metadata("style.width"))
  	});
  	
  	if(columns.length > 0){
  		//columns[0].style1("left",this.metadata("rowSelector")+1);
  		columns[0].style1("left",0);
  		for(var i = 1; i < columns.length; i++){
  			columns[i].style1("left",columns[i-1].dimension.left + columns[i-1].dimension.width + 5);
  		}
  	}
  }
  ,adjustColumnWidth:function(fromColumn){
  	
  	var fromIndex = fromColumn.metadata("index");
  	
  	var columns = this.getChildren();
// //console.log(this.declaredClass,"@@@@@@adjustColumnWidth","fromIndex",fromIndex,fromColumn.metadata("header"));
  	
  	for(var i = fromIndex; i < columns.length; i++){
  		if(i > 0){
  			columns[i].style1("left",columns[i-1].dimension.left + columns[i-1].dimension.width + 5);	
  		}				
  		this.gridBody.adjustColumnWidth(columns[i]);
  	}
  }
  ,adjustRowSelector:function(){
	  	//this.metadata("rowSelector");
  }
//  ,removeColumn:function(column){
//	  	this.gridBody.removeColumn(column);
//	  	this.removeChild(column);
//	  	construct.destroy(column.domNode);
//	  	// this.columnCount--;
//	  	this.adjustColumns();			
//	  	
//  }
  ,moveColumn:function(column){			
  	var from = column.metadata("index");  	
  	var columns = this.sortChildren();
  	array.forEach(columns,function(column,index){
  		column.metadata("index",index);
  	});
  	var to = column.metadata("index");
  	//columns[0].style1("left",this.metadata("rowSelector")+1);
  	columns[0].style1("left",0);
  	for(var i = 1; i < columns.length; i++){
  		columns[i].style1("left",columns[i-1].dimension.left + columns[i-1].dimension.width + 5);				
  	}
  	
  	if(from != to){				
  		this.gridBody.moveColumn(column,from, to);
  	}
  }
  // TODO:
  ,hideColumn:function(columnHeader){
	  // hide the column header
	  // hide the column cell
  }
  ,getResizableTargetContainer:function(){							
  	// return this.gridBody.domNode;
  	return this.domNode;
  }
  ,getContainerOutterBox:function(){
  	return {w:0,h:23};
  }
  ,createChild:function(){
	  	this._lastColumnIndex++;
	  	var columns = this._getChildren()
	  	var column = new agile.grid.GridHeader({header:'header' + this._lastColumnIndex,field:"f" + this._lastColumnIndex});
	  	var lastColumn = columns[columns.length - 1];
	  	column.metadata("style.left",lastColumn.dimension.left + lastColumn.dimension.width + 5);
	  	// column.metadata("style.width",lastColumn.dimension.width + 5);
	  	column.metadata("index",columns.length);
//	  	this.gridBody.addColumn(column);	  	
	  	return column;
  }
  ,getHeadColumns:function(){
	  return this._getChildren();
  }
  ,getData:function(){
	 return this.store == null?null:this.store.objectStore.data;	
  }
	,toHtml:function(params){
		var indent = this.indent(params.indentCount);
		var template = this.templateMap[params.sourceType];
		
		var param = this.getTemplateParameters(lang.mixin(lang.mixin({},params),{cascade:true}));
		param.thead = "<thead><tr>"+param.innerWidets+"</tr></thead>";
		param.tbody = params.cascade?this.gridBody.toHtml(params):"";
		
		template = lang.replace(template,param);
		return template;
	}
  [/@]